using UnityEngine;

public class CameraController : MonoBehaviour{
	
	public float maxDistance;
	public float moveRate;
	private Transform target;
	private Vector3 mousePos;
	private RaycastHit hitInfo;
	private Vector3 cameraPoint;
	private float sin;
	private float cos;
	private float targetPosition;
		
	public void SetTarget(Transform targetSet){
		target = targetSet;
	}
	
	void Update(){
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if(Physics.Raycast(ray, out hitInfo)){
			mousePos = new Vector3(hitInfo.point.x, target.position.y, hitInfo.point.z);
		}
		cameraPoint = (mousePos + target.position) / 2;
		if(TwoPointsDistance(target.position, mousePos) < maxDistance * 2){
			transform.position = Vector3.Lerp(transform.position, cameraPoint, moveRate * Time.deltaTime / 100);
		}
		else if(TwoPointsDistance(target.position, mousePos) >= maxDistance * 2){
			cameraPoint = GetMaxPointDistance(target.position, mousePos);
			transform.position = Vector3.Lerp(transform.position, cameraPoint, moveRate * Time.deltaTime / 100);
		}
	}
	
	float TwoPointsDistance(Vector3 point1, Vector3 point2){
		var distance = Mathf.Sqrt((point2.x - point1.x) * (point2.x - point1.x) + 
			(point2.z - point1.z) * (point2.z - point1.z));
		return distance;
	}
	
	Vector3 GetMaxPointDistance(Vector3 point1, Vector3 point2){
		sin = (point2.x - point1.x) / TwoPointsDistance(point2, point1);
		cos = (point2.z - point1.z) / TwoPointsDistance(point2, point1);
		var newPoint = new Vector3(target.position.x + sin * maxDistance, transform.position.y, target.position.z +  cos * maxDistance);
		return newPoint;
	}
}